package com.cy.algorithm.binarysearch;

/**
 * 二分查找算法
 *
 * @author chen_yu
 * @date 2020年12月13日17:03:19
 */
public class BinarySearch {

    public static void main(String[] args) {
        int[] a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 10};

        System.out.println(new BinarySearch().search(a, 3));
    }

    public int search(int[] arrays, int key) {
        if (arrays.length == 0) {
            return -1;
        }
        if (arrays.length == 1 && arrays[0] != key) {
            return -1;
        }
        int startIndex = 0;
        int endIndex = arrays.length - 1;
        while (startIndex < endIndex) {
            int midIndex = (endIndex + startIndex) / 2;
            if (arrays[midIndex] > key) {
                endIndex = midIndex;
            } else if (arrays[midIndex] < key) {
                startIndex = midIndex;
            } else {
                return midIndex;
            }
        }
        return -1;

    }

}
